package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService relationService;
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        // 1、保存基本数据
        this.save(attrEntity);

        // 2、保存关联关系
        if( attr.getAttrType().equals( ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()) && attr.getAttrGroupId() != null){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId( attr.getAttrGroupId());
            relationEntity.setAttrId( attrEntity.getAttrId());
            relationService.save(relationEntity);
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, String type, Long catId) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        Integer typeCode = ProductConstant.getTypeCode(type);
        queryWrapper.eq("attr_type", typeCode);
        if( catId != 0) {
            queryWrapper.and(w -> w.eq("catelog_id", catId));
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)) {
            queryWrapper.and(w -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> attrRespVos = new ArrayList<>();
        for (AttrEntity record : records) {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(record, attrRespVo);

            AttrAttrgroupRelationEntity relation = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", record.getAttrId()));

            if( relation != null && typeCode.equals(ProductConstant.AttrType.ATTR_TYPE_BASE.getCode())) {
                AttrGroupEntity attrGroup = attrGroupService.getById( relation.getAttrGroupId());
                if( attrGroup != null) {
                    attrRespVo.setAttrGroupName( attrGroup.getAttrGroupName());
                }
            }
            CategoryEntity category = categoryService.getById(record.getCatelogId());
            if( category != null) {
                attrRespVo.setCatelogName(category.getName());
            }
            attrRespVos.add(attrRespVo);
        }
        pageUtils.setList(attrRespVos);
        return pageUtils;
    }

    @Override
    @Transactional
    public void updateAttr(AttrVo attr) {
        // 更新属性
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);


        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrId(attr.getAttrId());
        relationEntity.setAttrGroupId(attr.getAttrGroupId());

        if( attr.getAttrType().equals( ProductConstant.AttrType.ATTR_TYPE_BASE.getCode())) {
            int count = attrAttrgroupRelationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if( count != 0) {
                attrAttrgroupRelationService.updateById(relationEntity);
            } else {
                attrAttrgroupRelationService.save(relationEntity);
            }
        }
    }

    @Override
    public AttrRespVo getAttr(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, attrRespVo);

        // 设置分组
        if( attrRespVo.getAttrType().equals(ProductConstant.AttrType.ATTR_TYPE_BASE.getCode())) {
            AttrAttrgroupRelationEntity relation = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if( relation!=null) {
                AttrGroupEntity attrGroup = attrGroupService.getById(relation.getAttrGroupId());
                attrRespVo.setAttrGroupId(attrGroup.getAttrGroupId());
                attrRespVo.setAttrGroupName(attrGroup.getAttrGroupName());
            }
        }
        // 设置分类
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrRespVo.setCatelogPath(catelogPath);
        return attrRespVo;
    }

    @Override
    public void removeAttr(Long... attrIds) {
        List<Long> ids = Arrays.asList(attrIds);
        this.removeByIds(ids);

        attrAttrgroupRelationService.remove(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_id", ids));
    }

    /**
     * 獲取到當前分組id為 <code>attrgroupId</code> 分組的所有屬性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attrGroups = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = new ArrayList<>();
        for (AttrAttrgroupRelationEntity attrGroup : attrGroups) {
            attrIds.add( attrGroup.getAttrId());
        }
        List<AttrEntity> attrEntities = new ArrayList<>();
        if( attrIds != null && attrIds.size() != 0) {
            attrEntities = this.listByIds(attrIds);
        }
        return attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] attrGroupRelationVos) {
        List<AttrAttrgroupRelationEntity> list = new ArrayList<>();
        for (AttrGroupRelationVo attrGroupRelationVo : attrGroupRelationVos) {
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attrGroupRelationVo, relation);
            list.add(relation);
        }
        baseMapper.deleteBatchRelation(list);

    }

    /**
     * 獲取當前分組沒有關聯的屬性
     * @param attrgroupId
     * @param params
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Long attrgroupId, Map<String, Object> params) {
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupId);
        // 分類Id
        Long catlogId = attrGroupEntity.getCatelogId();

        // 本分類下的分組
        List<AttrGroupEntity> attrGroupEntities = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catlogId));
        List<Long> groupIds = attrGroupEntities.stream().map(e -> e.getAttrGroupId()).collect(Collectors.toList());

        // 已有分組的屬性id
        List<Long> idsRelationsWithGroup = new ArrayList<>();
        if( groupIds != null && groupIds.size() > 0) {
            List<AttrAttrgroupRelationEntity> relationWithGroups = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
            for (AttrAttrgroupRelationEntity relationWithGroup : relationWithGroups) {
                idsRelationsWithGroup.add(relationWithGroup.getAttrId());
            }
        }

        // 本分類下的未有分組的屬性
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catlogId).eq("attr_type", ProductConstant.AttrType.ATTR_TYPE_BASE.getCode());
        if ( idsRelationsWithGroup!=null && !idsRelationsWithGroup.isEmpty()){
            attrEntityQueryWrapper.notIn("attr_id", idsRelationsWithGroup);
        }

        String key = (String) params.get("key");
        if ( StringUtils.isNotEmpty(key)) {
            attrEntityQueryWrapper.and(w -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), attrEntityQueryWrapper);
        return new PageUtils(page);
    }

    @Override
    public void insertBatchRelation(AttrGroupRelationVo[] attrGroupRelationVos) {
        List<AttrAttrgroupRelationEntity> entities = new ArrayList<>();
        for (AttrGroupRelationVo attrGroupRelationVo : attrGroupRelationVos) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attrGroupRelationVo, relationEntity);
            entities.add(relationEntity);
        }
        attrAttrgroupRelationService.saveBatch(entities);
    }


}